package com.sky.aspect;

import com.sky.annotation.AutoFillAnnotation;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFillAnnotation)")
    private void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFillAnnotation annotation = signature.getMethod().getAnnotation(AutoFillAnnotation.class);
        OperationType type = annotation.value();

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return ;
        }
        Object object = args[0];

        LocalDateTime currentTime = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();


        try {
            Method setUpdateTime = object.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = object.getClass().getDeclaredMethod("setUpdateUser", Long.class);
            switch (type) {
                case INSERT:
                    Method setCreateTime = object.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                    Method setCreateUser = object.getClass().getDeclaredMethod("setCreateUser", Long.class);
                    setUpdateTime.invoke(object, currentTime);
                    setUpdateUser.invoke(object, currentId);
                    setCreateTime.invoke(object, currentTime);
                    setCreateUser.invoke(object, currentId);
                    break;
                case UPDATE:
                    setUpdateTime.invoke(object, currentTime);
                    setUpdateUser.invoke(object, currentId);
                    break;
            }
        } catch(Exception e) {
            log.error("公共字段填充失败: {}", e.getMessage());
        }
    }
}
